<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input v-model="query.name" clearable size="small" placeholder="模糊搜索" style="width: 200px;"
                  class="filter-item" @keyup.enter.native="getData"/>
        <!--        <date-range-picker v-model="createTime" class="date-item" />-->
        <span>
              <el-button class="filter-item" size="mini" type="success" icon="el-icon-search"
                         @click="getData">搜索</el-button>
              <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetData">重置</el-button>
            </span>
      </div>
      <div class="crud-opts">
        <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left"/>
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="menuEdit(null)"
      >
        新增
      </el-button>
      <el-button
        slot="reference"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        @click="menuDelete"
      >
        删除
      </el-button>
      <el-button
        class="filter-item"
        size="mini"
        type="warning"
        icon="el-icon-download"
        @click="menuExport"
      >导出</el-button>
          <!--右侧-->
      <slot name="right"/>
    </span>
        <el-button-group class="crud-opts-right">
          <el-button
            size="mini"
            icon="el-icon-refresh"
            @click="getData"
          />
        </el-button-group>
      </div>
    </div>
    <!--表单渲染-->
    <el-dialog :append-to-body="false" :close-on-click-modal="false" :visible.sync="showEdit" title="编辑菜单" width="580px"
               :destroy-on-close="true">
      <el-form ref="menuModel" :inline="true" :model="menuModel" :rules="rules" size="small" label-width="80px">
        <el-form-item v-show="showMenuType" label="菜单类型" prop="type">
          <el-radio-group @change="changeTree" v-model="menuModel.type" size="mini" style="width: 178px">
            <el-radio-button label="0">目录</el-radio-button>
            <el-radio-button label="1">菜单</el-radio-button>
            <el-radio-button label="2">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="menuModel.type.toString() !== '2'" label="菜单图标" prop="icon">
          <el-popover
            placement="bottom-start"
            width="450"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selectIcon"/>
            <el-input slot="reference" v-model="menuModel.icon" style="width: 450px;" placeholder="点击选择图标" readonly>
              <svg-icon v-if="menuModel.icon" slot="prefix" :icon-class="menuModel.icon" class="el-input__icon"
                        style="height: 32px;width: 16px;"/>
              <i v-else slot="prefix" class="el-icon-search el-input__icon"/>
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-show="menuModel.type.toString() !== '2'" label="是否隐藏" prop="hidden">
          <el-radio-group v-model="menuModel.hidden" size="mini">
            <el-radio-button label="0">否</el-radio-button>
            <el-radio-button label="1">是</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="menuModel.type.toString() !== '2'" label="菜单标题" prop="name">
          <el-input v-model="menuModel.name"
                    :style=" menuModel.type.toString() === '0' ? 'width: 450px' : 'width: 178px'" placeholder="菜单标题"/>
        </el-form-item>
        <el-form-item v-if="menuModel.type.toString() === '2'" label="按钮名称" prop="name">
          <el-input v-model="menuModel.name" placeholder="按钮名称" style="width: 178px;"/>
        </el-form-item>
        <el-form-item v-if="menuModel.type.toString() !== '2'" label="路由地址" prop="path">
          <el-input v-model="menuModel.path" placeholder="路由地址" style="width: 178px;"/>
        </el-form-item>
        <el-form-item label="菜单排序" prop="sort">
          <el-input-number v-model.number="menuModel.sort" :min="0" :max="999" controls-position="right"
                           style="width: 178px;"/>
        </el-form-item>
        <el-form-item v-show=" menuModel.type.toString() === '1'" label="组件路径" prop="component">
          <el-input v-model="menuModel.component" style="width: 178px;" placeholder="匹配组件内Name字段"/>
        </el-form-item>
        <el-form-item v-show=" menuModel.type.toString() === '1'" label="组件名称" prop="componentPath">
          <el-input v-model="menuModel.componentPath" style="width: 178px;" placeholder="组件名称"/>
        </el-form-item>
        <el-form-item label="上级类目" prop="menuParentId">
          <treeselect
            @select="changeParentNode"
            v-model="menuModel.menuParentId"
            :options="menus"
            :load-options="loadMenus"
            style="width: 450px;"
            placeholder="选择上级类目"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="showConfirm">
        <el-button type="text" @click="menuClear">取消</el-button>
        <el-button type="primary" @click="menuAdd">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      lazy
      :load="getSubComponets"
      :data="menuList"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      row-key="id"
      @select="batchEdit"
      @select-all="batchEdit"
      @selection-change="batchEdit">
      <el-table-column type="selection" width="55"/>
      <el-table-column :show-overflow-tooltip="true" label="菜单标题" width="125px" prop="name"/>
      <el-table-column prop="icon" label="图标" align="center" width="60px">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon ? scope.row.icon : ''"/>
        </template>
      </el-table-column>
      <el-table-column prop="menuSort" align="center" label="排序">
        <template slot-scope="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="path" label="组件路径"/>
      <el-table-column prop="hidden" label="可见" width="75px">
        <template slot-scope="scope">
          <span v-if="scope.row.hidden">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建日期"
        width="135">
      </el-table-column>
      <el-table-column v-permission="['admin','menu:edit','menu:del']" label="操作" width="130px" align="center"
                       fixed="right">
        <template slot-scope="scope">
          <el-button :disabled="false" size="mini" type="primary" icon="el-icon-edit" @click="menuEdit(scope.row)"/>
          <Poptip style="margin-left: 10px" @on-ok="menuRm(scope.row)" transfer confirm title="确认删除?">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
            />
          </Poptip>
        </template>

      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  menusPage,
  subMenus,
  saveMenus,
  editMenus,
  delMenus,
  getParentId,
  getParentInfo,
  buildMenus
} from '@/api/system/menu'
import IconSelect from '@/components/IconSelect'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {LOAD_CHILDREN_OPTIONS} from '@riophae/vue-treeselect'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import DateRangePicker from '@/components/DateRangePicker'
import dateUtils from '@/utils/dateUtils'
import appUtils from '@/utils/appUtils'
import log from '@/views/system/timing/log'


// crud交由presenter持有
//  const defaultForm = { id: null, title: null, menuSort: 999, path: null, component: null, componentName: null, iframe: false, roles: [], pid: 0, icon: null, cache: false, hidden: false, type: 0, permission: null }
export default {
  name: 'Menu',
  components: {Treeselect, IconSelect, crudOperation, rrOperation, udOperation, DateRangePicker},
  // cruds() {
  //   return CRUD({ title: '菜单', url: 'admin/menu/page', crudMethod: { ...crudMenu }})
  // },
  //    mixins: [ parseTime()],
  data() {
    return {
      showConfirm: true,
      treeLoading: false,
      menus: [],
      // 是否显示菜单类型
      showMenuType: true,
      //表单提交
      menuModel: {
        id: 0,
        type: 4,
        icon: null,
        hidden: 0,
        name: null,
        path: null,
        sort: null,
        component: null,
        componentPath: null,
        menuParentId: null,
        menuParentName: null,
        hasChildren: null,
        menuName:null
      },
      menuList: [],
      sunMenuList: [],
      createTime: null,
      query: {
        name: null,
        page: 0,
        size: 10,
        current: 1,
        blurry: null,
        startTime: null,
        endTime: null
      },
      showEdit: false,
      showDel: false,
      permission: {
        add: ['admin', 'menu:add'],
        edit: ['admin', 'menu:edit'],
        del: ['admin', 'menu:del']
      },
      rules: {
        name: [
          {required: true, message: '请输入标题', trigger: 'blur'}
        ],
        path: [
          {required: true, message: '请输入地址', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {

    //添加或编辑
    menuEdit(row) {
      if (row == null) {
        this.showEdit = true
        this.showMenuType = true
        this.menuModel.type = 0
        this.menuModel.icon = null
        this.menuModel.hidden = 0
        this.menuModel.name = null
        this.menuModel.path = null
        this.menuModel.sort = 0
        this.menuModel.component = null
        this.menuModel.componentPath = null
        this.menuModel.menuParentId = null
        this.menus = [{id: 0, label: '根目录', children: null}]
      } else {
        this.showEdit = true
        this.showMenuType = false
        this.menuModel.hasChildren = row.hasChildren
        if (row.menuParentId === 0) {
          this.menus = [{id: 0, label: '根目录', children: null}]
          this.menuModel.id = row.id
          this.menuModel.type = row.type
          this.menuModel.icon = row.icon
          this.menuModel.menuParentId = 0
          this.menuModel.name = row.name,
            this.menuModel.path = row.path,
            this.menuModel.sort = row.sort,
            this.menuModel.component = row.component,
            this.menuModel.componentPath = row.componentPath
        } else {
          this.menuModel.id = row.id
          this.menuModel.type = row.type
          this.menuModel.icon = row.icon
          this.menuModel.name = row.name
          this.menuModel.path = row.path
          this.menuModel.sort = row.sort
          this.menuModel.component = row.component
          this.menuModel.componentPath = row.componentPath
          // 回显上级目录名称
          let that = this
          getParentInfo(row.id).then(res => {
            if (res.state) {
              this.menuModel.menuParentId = res.data.id
              that.menus = [{id: res.data.id, label: res.data.menuName, children: null}]
            }
          })
        }
      }
    },
    //  获取数据
    getData() {
      if (this.createTime != null && this.createTime !== '') {
        this.query.startTime = this.createTime[0]
        this.query.endTime = this.createTime[1]
      }
      menusPage(this.query).then(res => {
        if (res.state) {
          this.menuList = res.data.records
        }
      }).catch(err => {

      })
    },
    //重置数据
    resetData() {
      if (this.query.name != null || this.query.name != '') {
        this.query.name = null
      }
      if (this.createTime != null || this.createTime != '') {
        this.createTime = 0
      }
      this.getData()
    },
    //  获取当前路由的上级目录
    loadMenus({action, parentNode, callback}) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        //第一层数据
        if (parentNode.id === 0) {
          // 如果为添加目录，不用加载子菜单
          if (this.menuModel.type == 0) {
            this.menus = [{id: 0, label: '根目录'}]
          } else {
            // menusPage(this.query).then(res => {
            //   if (res.state) {
            //     this.menus = res.data.records
            //     // parentNode.children = this.menus
            //   }
            // })
            buildMenus(false).then(res => {
              if (res.state) {
                this.menus = res.data
              }
            })
          }
        } else {
          subMenus(JSON.stringify(parentNode)).then(res => {
            parentNode.children = res.data.map(function (obj) {
              if (!obj.leaf) {
                obj.children = null
              }
              return obj
            })
            setTimeout(() => {
              callback()
            }, 100)
          })
        }
      }
    },
    //添加按钮
    menuAdd() {
      if (this.menuModel.name === '' || this.menuModel.name == null) {
        appUtils.showError("请输入名称")
        return false;
      }
      if (this.menuModel.path === '' || this.menuModel.path == null) {
        if (this.menuModel.type.toString() !== '2') {
          appUtils.showError("请输入地址")
          return false;
        }
      }
      var that = this
      if (this.menuModel.id === 0) {
        this.menuModel.menuName=this.menuModel.name
        saveMenus(JSON.stringify(this.menuModel)).then(res => {
          this.showEdit = false
          that.$refs['menuModel'].resetFields()
          if (res.state) {
            appUtils.showSuccess("添加成功")
            this.getData()
            // this.$router.go(0);
          } else {
            appUtils.showError("添加失败")
          }
        })
      } else {
        editMenus(JSON.stringify(this.menuModel)).then(res => {
          this.showEdit = false
          if (res.state) {
            appUtils.showSuccess("编辑成功")
            that.$refs['menuModel'].resetFields()
            this.getData()
            // this.$router.go(0);

          }
        })
      }

    },
    menuDelete() {

    },
    menuExport() {

    },
    //批量方法
    batchEdit() {

    },
    //  取消弹窗
    menuClear() {
      this.$refs['menuModel'].resetFields()
      this.showEdit = false
    },
    //  删除弹出
    menuRm(row) {
      delMenus(JSON.stringify(row)).then(res => {
        if (res.state) {
          appUtils.showSuccess("删除成功")
          this.getData()
          this.$router.go(0);
        } else {
          appUtils.showError("删除失败")
        }
      })
    },
    //  添加时选中图标
    selectIcon(row) {
      this.menuModel.icon = row
    },
    //  获取选中菜单的子组件
    getSubComponets(tree, treeNode, resolve) {
      subMenus(JSON.stringify(tree)).then(res => {
        if (res.state) {
          resolve(res.data)
        } else {
          appUtils.showError("错误")
        }
      }).catch(err => {
      })
    },
    // 当切换目录类型时，需要将菜单树的数据置空
    changeTree(data) {
      this.menuModel = {
        id: 0,
        type: data,
        icon: null,
        hidden: null,
        menuName:null,
        name: null,
        path: null,
        sort: null,
        component: null,
        componentPath: null,
        menuParentId: null,
        menuParentName: null,
        hasChildren: null
      }
      this.menus = [{id: 0, label: '根目录', children: null}]
    },
    // 监听目录的选择
    changeParentNode(data1, data2) {
      let parentId = data1.menuParentId
      let id = data1.id
      // 目录只能选择0
      // 菜单只能选择目录
      // 权限只能选择菜单
      if (this.menuModel.type === '0') {
        if (id !== 0) {
          appUtils.showError("您必须选择根目录")
          this.showConfirm = false
          return false;
        } else {
          this.showConfirm = true
          return true;
        }
      }
      if (this.menuModel.type === '1') {
        if (id == 0 || parentId !== 0) {
          appUtils.showError("您必须选择一级目录")
          this.showConfirm = false
          return false;
        } else {
          this.showConfirm = true
          return true;
        }
      }
      if (this.menuModel.type === '2') {
        if (parentId === 0 || id === 0) {
          appUtils.showError("您只能选择二级目录添加权限")
          this.showConfirm = false
          return false;
        } else {
          this.showConfirm = true
          return true;
        }
      }
    }
  },
  mounted() {
    this.getData()
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}

::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
